package com.xiaoming.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaoming.SpringContextUtils;
import com.xiaoming.User;
import com.xiaoming.UserService;
import com.xiaoming.service.UserServiceImpl;
import com.xiaoming.utils.RpcRequest;
import com.xiaoming.utils.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

public class UserServerHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest rpcRequest =(RpcRequest)msg;
        String className = rpcRequest.getClassName();
        String methodName = rpcRequest.getMethodName();
        Object[] parameters = rpcRequest.getParameters();
        Class<?>[] parameterTypes = rpcRequest.getParameterTypes();

        Class<?> aClass = Class.forName(className);

        UserService o = (UserServiceImpl) SpringContextUtils.getBean(aClass);
        Method method = aClass.getMethod(methodName, parameterTypes);
        method.setAccessible(true);
        parameters[0] =JSON.toJavaObject((JSONObject) parameters[0],User.class);
        //反射调用
        Object result = method.invoke(o, parameters);

        //返回客户端响应信息
        RpcResponse rpcResponse = new RpcResponse();
        rpcResponse.setData(result);
        rpcResponse.setClientName("服务端2");
        rpcResponse.setCode("OK");
        rpcResponse.setMessage("请求成功");
        ctx.writeAndFlush(rpcResponse);
    }
}
